<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>
</head>
<body>

<textarea id="responseText" style="height: 300px; width: 300px"></textarea>
<input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''">
<br><br>
<textarea id="message" style="height: 100px; width: 300px"></textarea>
<input type="button" value="发送消息" onclick="send()">

</body>
<script>
    let socket;
    if (window.WebSocket) {
        socket = new WebSocket('ws://localhost:9000/hello')
        socket.onmessage = ev => {
            let rt = document.getElementById('responseText')
            rt.value = rt.value + '\n' + ev.data
        }
        socket.onopen = ev => {
            let rt = document.getElementById('responseText')
            rt.value = '连接开启了...'
        }
        socket.onclose = ev => {
            let rt = document.getElementById('responseText')
            rt.value = '连接关闭了...'
        }
    } else {
        alert('当前浏览器不支持WebSocket....')
    }

    function send() {
        if (!socket) {
            return;
        }
        let msg = document.getElementById('message')
        if (socket.readyState == WebSocket.OPEN) {
            socket.send(msg.value)
            msg.value = ''
        }
    }
</script>
</html>
